import * as types from '../mutation-types';
import Util from '../../common/util.js';

//建议对于getters,actions都加上模块名
// initial state
const state = {
  token: {}, //TOKEN INFO 
  user: {}, //当前用户信息
  menu: {}, //菜单信息
  headerMenu: [], //顶部菜单信息
  navMenu: [], //左边菜单信息
  navActive: { //左边菜单激活
  	openNames: [],
  	activeName: null
  },
  menuNameMap: {}, //菜单名称MAP(routeName-indexPath)
  menuIndexMap: {}, //菜单名称MAP(indexPath-routeName)
  perms: [], //权限信息
  params: {}, //初始化的其他参数信息
  activeMenu: { //激活的菜单信息(顶部)
  	header: 0,
  	navPath: ''
  },
  unReadmessageCount:null, //未读消息数 
  currentLanguage:'', //当前所选择的语言
}

// getters
const getters = {
  auth_token: state => state.token,
  auth_tenantId: state => state.user.tenantId,
  auth_token_id: state => state.token.tokenValue,
  auth_refresh_token_id: state => state.token.refreshTokenValue,
  auth_header_menus: state => state.headerMenu,
  auth_nav_menus: state => state.navMenu,
  auth_menus: state => state.menu,
  auth_activeMenu_header: state => state.activeMenu.header, //顶部激活菜单
  auth_activeMenu_navPath: state => state.activeMenu.navPath, //顶部左边菜单
  auth_nav_active: state => state.navActive, //激活的菜单信息(左边)
  auth_nav_index_map: state => state.menuIndexMap, //最后一层业务菜单indexPath-routeName
  auth_context_params: state => state.params, //获取其他参数
  auth_username:function(state){
  	if(state.user) {
  		return state.user.userName;
  	}
  	return '';
  },
  auth_loginName:function(state){
    return state.user?state.user.loginName:'';
  },
  auth_user: state => state.user,
  auth_un_readmessage_count: state => state.unReadmessageCount, //未读消息数
  // 当前所选择的语言
  currentLanguage:state=>state.currentLanguage, 
}

// actions(异步操作)
const actions = {
  //刷新缓存TOKEN
  authFlushToken ({ commit, state }) {
    commit(types.AUTH_FLUSH_TOKEN);
  },
  //登出服务
  authLogout({ commit, state }) {
    commit(types.AUTH_LOGOUT);
  },
  //用户登录服务
  authLogin({ commit, state }, data_) {
    commit(types.AUTH_LOGIN, data_);
  },
  //顶部菜单点击切换动作
  authHeadMenuClick({ commit, state }, data_) {
    commit(types.AUTH_HEAD_MENU_CLICK, data_);
  },
  //更新菜单
  authUpdateMenu({ commit, state }, params_) {
  	commit(types.AUTH_UPDATE_MENU, params_);
  },
  /**
   * 手动触发修改菜单
   */
  authHandUpdateMenu({ commit, state }, params_) {
  	commit(types.AUTH_UPDATE_MENU, params_);
  	commit(types.AUTH_HAND_UPDATE_MENU, params_);
  },
  //查询未读消息数量
  authUnReadmessageCount({ commit, state }, data_) {
    commit(types.AUTH_UN_READMESSAGE_COUNT, data_);
  },
  /**
   * 查询当前的所选择的语言
   */
  currentLanguage({commit,state},data_){
	commit(types.CURRENT_LANGUAGE,data_);
  }
}

// mutations(同步操作)
const mutations = {
  //刷新缓存TOKEN
  [types.AUTH_FLUSH_TOKEN] (state) {
      let tokenData = localStorage.getItem(Util.tokenKey());
      state.token = JSON.parse(tokenData);
  },
  //登录操作
  [types.AUTH_LOGIN] (state, data_) {
      state.user = data_.userBO;
      state.perms = data_.permissionList;
      let menu_ = data_.menuTree;
      state.menu = menu_;
      state.params = data_.paramMap;
      buildHeadMenus(state, menu_);
      buildMenuMap(state, menu_);
  },
  //登出
  [types.AUTH_LOGOUT] (state, data_) {
  		state.token = {};
  		state.user = {};
  		state.menu = {};
  		state.headerMenu = {};
  		state.navMenu = {};
  		state.perms = {};
			localStorage.clear();  	
  },  
  //顶部菜单点击切换
  [types.AUTH_HEAD_MENU_CLICK] (state, data_) {
      let activeIndex_ = data_.index;
      let headerMenu_ = state.headerMenu;
      if(activeIndex_ > headerMenu_.length) {
      	return;
      }
      state.activeMenu.header = activeIndex_;
      //更新左边菜单
      buildNavMenus(state, activeIndex_);
      //默认跳转到第一个菜单
      let firstIndexPath_ = activeIndex_ + '_0_0';
      //更新左边菜单
  		state.navActive = { //左边菜单激活
		  	openNames: [activeIndex_ + '_0'],
		  	activeName: firstIndexPath_
		  };
		  let routeName_ = state.menuIndexMap[firstIndexPath_];
		  if(routeName_) {
		  	let router_ = data_.router;
		  	router_.push({name: routeName_});
		  }
  },
  /**
   * 手动更新菜单
   */
  [types.AUTH_HAND_UPDATE_MENU](state, params_) {
  	let router_ = params_.router;
  	let curr_ = params_.curr;
  	let routeName_ = curr_.name;
  	let query = curr_.query || {};
  	state.activeMenu.navPath = new Date().getTime();
		router_.push({name: routeName_, query});
  },
  //更新菜单
  [types.AUTH_UPDATE_MENU](state, params_) {
  	let router_ = params_.router;
  	let curr_ = params_.curr;
  	let routeName_ = curr_.name;
  	let routeNameMap_ = state.menuNameMap;
  	let indexPath_ = routeNameMap_[routeName_];
  	let activeIndex_ = 0;
  	if(indexPath_) {
  		let indexPaths_ = indexPath_.split('_');
  		activeIndex_ = indexPaths_[0];
  		//更新左边菜单
  		state.navActive = { //左边菜单激活
		  	openNames: [arrayAppendToStr(indexPaths_, 2)],
		  	activeName: indexPath_
		  };
  	}
  	state.activeMenu.header = activeIndex_;
  	//更新菜单
		buildNavMenus(state, activeIndex_);
  },
  //查询未读消息数量
  [types.AUTH_UN_READMESSAGE_COUNT] (state, data_) {
      state.unReadmessageCount = data_;
  },

  //查询当前所选择的语言类型
  [types.CURRENT_LANGUAGE](state,data_){
	  state.currentLanguage=data_;
  }
}


/**
 * 拼接字符串
 * @param {Object} arrs_
 * @param {Object} index_
 */
function arrayAppendToStr(arrs_, index_) {
	let str_ = '';
	for(let i = 0; i < index_; i++) {
		if(0 != i) {
			str_ += '_';
		}
		str_ += arrs_[i];
	}
	return str_;
}

/**
 * 构建菜单
 * @param {Object} state
 * @param {Object} menu_
 */
function buildHeadMenus(state, menu_) {
	if(menu_) {
		let mlist_ = menu_.children;
		if(mlist_) {
			//存在菜单元素
			let mlistLength_ = mlist_.length;
			for(let i = 0; i < mlistLength_; i++) {
				let m_ = mlist_[i];
				let mType_ = m_.tree.wType;
				if(1 == mType_) {
					//模块菜单
					state.headerMenu.push({
						index: i,
						key: m_.key,
						label: m_.label
					});
				}
			}
			if(mlistLength_ > 0) {
				let activeIndex_ = state.activeMenu.header;
				buildNavMenus(state, activeIndex_);
			}
		}
	}
};

/**
 * 激活的顶部菜单
 * @param {Object} state
 * @param {Object} activeIndex_
 */
function buildNavMenus(state, activeIndex_) {
	let menu_ = state.menu;
	if(menu_) {
		let mlist_ = menu_.children;
		if(mlist_) {
			let curMenu_ = mlist_[activeIndex_];
			let navMenuList_ = [];
			loopNavMenu(curMenu_, navMenuList_);
			state.navMenu = navMenuList_;
//			debugger;
		}
	}	
}

function loopNavMenu(curMenu_, nvaMenuList_) {
//	debugger;
	if(curMenu_) {
		let mlist_ = curMenu_.children;
		if(mlist_) {
			let mlistLength_ = mlist_.length;
			for(let i = 0; i < mlistLength_; i++) {
				let m_ = mlist_[i];
				let menudata_ = {
					data: {
						key: m_.key,
						label: m_.label,
						url: m_.tree.url,
						indexPath: m_.indexPath
					},
					chs: []
				};
				nvaMenuList_.push(menudata_);
				loopNavMenu(m_, menudata_.chs);
			}
		}
	}
}

/**
 * 构建菜单MAP
 * @param {Object} state
 * @param {Object} menu_
 */
function buildMenuMap(state, menu_) {
	let menuNameMap = {};
	let menuIndexMap = {};
	buildDisMenuMap(menu_, menuNameMap, menuIndexMap);
	state.menuNameMap = menuNameMap;
	state.menuIndexMap = menuIndexMap;
}
/**
 * 递归构建菜单MAP
 * @param {Object} menu_
 * @param {Object} menuNameMap
 */
function buildDisMenuMap(menu_, menuNameMap_, menuIndexMap_) {
	if(menu_.tree) {
		let routeName = menu_.tree.url;
		if(!Util.vad.isBlank(routeName)) {
			let indexPath_ = menu_.indexPath;
			menuNameMap_[routeName] = indexPath_;
			menuIndexMap_[indexPath_] = routeName;
		}
	}
	if(menu_.children) {
		let childMenus = menu_.children;
		for(let i = 0; i <  childMenus.length; i++) {
			let childMenu = childMenus[i];
			buildDisMenuMap(childMenu, menuNameMap_, menuIndexMap_);
		}
	}	
}

export default {
  state,
  getters,
  actions,
  mutations
}